import axios from 'axios';
import { getToken } from '@/utils/auth';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_QINIU_URL,
  // 超时
  timeout: 10000,
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    config.headers['Authorization'] = getToken();
    return config;
  },
  (error) => {
    console.log(error);
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    if (res.data.code == 200) {
      return res.data;
    } else {
      Message({
        message: '七牛云存储服务异常',
        type: 'error',
        duration: 5 * 1000,
      });
      return Promise.reject(error);
    }
  },
  (error) => {
    let { message } = error;
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
